//
//  YZMStopStockDetailViewController.m
//  YZMicroStock
//
//  Created by apple on 16/11/14.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMStopStockDetailViewController.h"
#import "YZMCombLabelView.h"
#import "YZClient.h"
#import "YZMTradeSettlementModel.h"
#import "YZMTradeSTDetailModel.h"
#import "YZMResultView.h"
#import "NSNumber+Utils.h"
#import "UILabel+Color.h"
#import "Masonry+Utils.h"
#import "YZMWebViewService.h"
#import "MBProgressHUD+Utils.h"
#import <DateTools/DateTools.h>
#import <AFNetworking/AFNetworkReachabilityManager.h>
#import "YZMSaleTradeModel.h"

@interface YZMStopStockDetailViewController ()
@property (nonatomic, strong) YZMSaleTradeModel *model;
@property (nonatomic, strong) YZMTradeSTDetailModel *tradeDetail;
@property (nonatomic, strong) YZMResultView *resultView;

@end

@implementation YZMStopStockDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"策略详情";     //停牌策略的详情
    self.view.backgroundColor = [YZMAppStyle appBackgroundColor];
    
    self.resultView = [YZMResultView new];
    self.resultView.status = YZM_RESULT_STATUS_FOR_NORMAL;
    __weak __typeof(&*self) weakSelf = self;
    self.resultView.retryAction = ^{
        
        [weakSelf fetchStockDetail];
    };
    [self.view addSubview:self.resultView];
    [self.resultView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:)
                                                 name:AFNetworkingReachabilityDidChangeNotification object:nil];
    [self fetchStockDetail];
    // Do any additional setup after loading the view.
}

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark -- network

- (void)reachabilityChanged:(NSNotification *)note{
    if (!kNetworkNotReachability) {
        
        [self fetchStockDetail];
    }
}

- (void)fetchStockDetail{
    
    [YZClient td_fetchTradeSettlementDetailWithID:self.model.tid success:^(NSURLResponse *response, id responseObject) {
        
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            
            [[NSNotificationCenter defaultCenter] removeObserver:self];
            self.resultView.status = YZM_RESULT_STATUS_FOR_NORMAL;
            self.tradeDetail = topModel.data;
            [self createObjects];
            
        }else{
            
            self.resultView.status = YZM_RESULT_STATUS_FOR_ABNORMAL;
        }
        
    } failure:^(NSError *error) {
        [self.resultView syncStatusWithError:error];
    }];
}

#pragma mark -- event

- (void)clickToShowAgreement:(UIButton *)sender{
    
    if (!YZMUserServiceInstance.isValidate) {
        
        [MBProgressHUD showMessage:@"网络恢复中，请稍后重试"];
        return;
    }
    
    if (self.model.schemeId > 0) {
        
        [YZMWebViewService openCooperationDelegateWithTradeID:self.tradeDetail.tid withType:YZM_TRADE_TYPE_FOR_A_STOCK_D];
    } else {
        
        [YZMWebViewService openCooperationDelegateWithTradeID:self.tradeDetail.tid withType:YZM_TRADE_TYPE_FOR_A_STOCK];
    }
}

#pragma mark -- ui

- (void)createObjects{
    
    UIScrollView *sv = [UIScrollView new];
    [self.view addSubview:sv];
    [sv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    UIView *containerView = [UIView new];
    [sv addSubview:containerView];
    [containerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.width.equalTo(sv);
    }];
    
    UIView *lastView = nil;
    NSArray *array = @[[self firstPartView],[self secondPartView],[self thirdPartView],[self fourthPartView]];
    for (UIView *partView in array) {
        
        [containerView addSubview:partView];
        [partView mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.left.right.equalTo(containerView);
            if (lastView) {
                
                make.top.equalTo(lastView.mas_bottom);
            }else{
                
                make.top.equalTo(containerView);
            }
        }];
        lastView = partView;
    }
    
    [containerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(lastView);
    }];
}

- (UIView *)firstPartView{
    
    UIView *customView = [UIView new];
    
    UILabel *label = [YZMAppStyle labelWithFont:[YZMAppStyle smallSizeFont] andColor:[YZMAppStyle colorForWhite]];
    label.text = [NSString stringWithFormat:@"JQ%@",@(self.model.tid)];
    [customView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.equalTo(customView).offset(15);
        make.bottom.equalTo(customView).offset(-15);
    }];
    
    UIButton *agreementBT = [UIButton new];
    [agreementBT setTitle:@"  合约协议  " forState:UIControlStateNormal];
    [agreementBT setTitleColor:[YZMAppStyle colorForBlueText] forState:UIControlStateNormal];
    [agreementBT.titleLabel setFont:[YZMAppStyle smallSizeFont]];
    [agreementBT addTarget:self action:@selector(clickToShowAgreement:) forControlEvents:UIControlEventTouchUpInside];
    [customView addSubview:agreementBT];
    [agreementBT mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(customView);
        make.left.equalTo(label.mas_right).offset(4);
    }];
    
    return [self unitViewWithString:@"策略交易号" andCustomView:customView];
}

- (UIView *)secondPartView{
    
    UIView *customView = [UIView new];
    
    UILabel *leftFirstLB = [YZMAppStyle labelWithSmallLightGray];
    leftFirstLB.text = @"投资人";
    [customView addSubview:leftFirstLB];
    [leftFirstLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.equalTo(customView).offset(15);
    }];
    
    UILabel *rightFirstLB = [YZMAppStyle labelWithSmallWhite];
    rightFirstLB.text = [self.tradeDetail.investorUsername stringByAppendingFormat:@"(ID:%@)",@(self.tradeDetail.investorUserId)];
    [customView addSubview:rightFirstLB];
    [rightFirstLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(leftFirstLB);
        make.left.equalTo(leftFirstLB.mas_right).offset(10);
    }];
    
    UILabel *leftSecondLB = [YZMAppStyle labelWithSmallLightGray];
    leftSecondLB.text = @"点买人";
    [customView addSubview:leftSecondLB];
    [leftSecondLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(leftFirstLB.mas_bottom).offset(10);
        make.left.equalTo(leftFirstLB);
        make.bottom.equalTo(customView).offset(-15);
    }];
    
    UILabel *rightSecondLB = [YZMAppStyle labelWithSmallWhite];
    rightSecondLB.text = [self.tradeDetail.username stringByAppendingFormat:@"(ID:%@)",@(self.tradeDetail.userId)];
    [customView addSubview:rightSecondLB];
    [rightSecondLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(leftSecondLB);
        make.left.equalTo(rightFirstLB);
    }];
    
    return [self unitViewWithString:@"交易合作" andCustomView:customView];
    
}

- (UIView *)thirdPartView{
    UIView *customView = [UIView new];
    UIView *leftStackView = [self gridStackViewWithArray:@[@"股票名称",@"买入价格",@"买入类型",@"买入时间",@"持仓天数",@"综合费"] andTextColor:[YZMAppStyle colorForLightGrayText]];
    [customView addSubview:leftStackView];
    [leftStackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo(customView).offset(15);
        make.bottom.equalTo(customView).offset(-15);
    }];
    
    UIView *firstStackView;
    firstStackView = [self gridStackViewWithArray:@[self.tradeDetail.stockName,@(self.tradeDetail.buyPriceDeal).p02fString,@"即时成交",[self.tradeDetail.dealTime formattedDateWithFormat:@"YYYY-MM-dd"],[NSString stringWithFormat:@"%@个交易日", @(self.tradeDetail.holdDays)],@(self.tradeDetail.serviceCharge).p02fString] andTextColor:[YZMAppStyle colorForWhite]];
    [customView addSubview:firstStackView];
    [firstStackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(leftStackView.mas_right).offset(10);
        make.top.equalTo(leftStackView);
        
    }];
    
    NSArray *valueArray=@[@(self.tradeDetail.money).p02fString,@(self.tradeDetail.sellPriceDeal).p02fString,@"即时成交",[self.tradeDetail.closeTime formattedDateWithFormat:@"YYYY-MM-dd"],[NSString stringWithFormat:@"%@股",@(self.tradeDetail.volumeDeal)],[@(self.tradeDetail.deferCharge).p02fString stringByAppendingFormat:@"(%@次)",@(self.tradeDetail.holdDays-2)]];
    if (self.model.schemeId>0) {
        valueArray=@[@(self.tradeDetail.money).p02fString,@(self.tradeDetail.sellPriceDeal).p02fString,@"即时成交",[self.tradeDetail.closeTime formattedDateWithFormat:@"YYYY-MM-dd"],[NSString stringWithFormat:@"%@股",@(self.tradeDetail.volumeDeal)],@""];
    }
    
    UIView *rightStackView = [self gridStackViewWithArray:valueArray andTextColor:[YZMAppStyle colorForWhite]];
    [customView addSubview:rightStackView];
    [rightStackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(customView).offset(15);
        make.right.equalTo(customView).offset(-15);
    }];
    NSArray *nameArray=@[@"交易本金",@"卖出价格",@"卖出类型",@"卖出时间",@"交易数量",@"递延费"];
    if (self.model.schemeId>0) {
        nameArray=@[@"交易本金",@"卖出价格",@"卖出类型",@"卖出时间",@"交易数量",@""];
    }
    
    UIView *secondStackView = [self gridStackViewWithArray:nameArray andTextColor:[YZMAppStyle colorForLightGrayText]];
    [customView addSubview:secondStackView];
    [secondStackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(rightStackView);
        make.right.equalTo(rightStackView.mas_left).offset(-10);
    }];
    
    UIView *line = [secondStackView viewWithTag:99];
    line.backgroundColor = [YZMAppStyle colorForSplitLine];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(customView).offset(15);
        make.right.equalTo(customView).offset(-15);
        make.height.mas_equalTo(0.5);
    }];
    
    return [self unitViewWithString:@"交易明细" andCustomView:customView];
}

- (UIView *)gridStackViewWithArray:(NSArray *)array andTextColor:(UIColor *)textColor{
    
    UIView *stackView = [UIView new];
    
    UIView *lastView = nil;
    for (NSString *content in array) {
        
        NSInteger index = [array indexOfObject:content];
        if (index == array.count-1 ) {
            
            UIView *line = [UIView new];
            line.tag = 99;
            [stackView addSubview:line];
            [line mas_makeConstraints:^(MASConstraintMaker *make) {
                
                make.top.equalTo(lastView.mas_bottom).offset(15);
            }];
            
            lastView = line;
        }
        
        UILabel *label = [YZMAppStyle labelWithFont:[YZMAppStyle smallSizeFont] andColor:textColor];
        label.text = content;
        [stackView addSubview:label];
        
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(stackView);
            make.width.lessThanOrEqualTo(stackView);
            if (lastView) {
                
                make.top.equalTo(lastView.mas_bottom).offset(15);
            }else{
                
                make.top.equalTo(stackView);
            }
        }];
        
        lastView = label;
    }
    
    [stackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(lastView);
    }];
    
    return stackView;
}

- (UIView *)fourthPartView{
    
    UIView *customView = [UIView new];
    
    YZMCombLabelView *leftFirstView = [YZMCombLabelView new];
    leftFirstView.leftLB.text = @"策略盈亏";
    [leftFirstView.rightLB setTextColorWithGreatNumber:self.tradeDetail.profitTotal andSmallNumber:0.0];
    leftFirstView.rightLB.text = @(self.tradeDetail.profitTotal).p02fString;
    
    [customView addSubview:leftFirstView];
    [leftFirstView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo(customView).offset(15);
        make.bottom.equalTo(customView).offset(-15);

    }];
    
    
    return [self unitViewWithString:@"点买人盈亏分配" andCustomView:customView];
}


- (UIView *)unitViewWithString:(NSString *)title andCustomView:(UIView *)customView{
    
    UIView *view = [UIView new];
    
    UILabel *titleLB = [YZMAppStyle labelWithSmallWhite];
    titleLB.text = title;
    [view addSubview:titleLB];
    [titleLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo(view).offset(15);
    }];
    
    customView.backgroundColor = [YZMAppStyle colorForMain];
    [view addSubview:customView];
    [customView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLB.mas_bottom).offset(10);
        make.left.right.bottom.equalTo(view);
    }];
    
    return view;
}

#pragma mark - controller manager support

- (void)updateWithParams: (NSDictionary *)params
{
    self.model = params[@"trade"];
}

+ (instancetype)createWithParams: (NSDictionary *)params
{
    YZMStopStockDetailViewController *ctrl = [[self alloc] init];
    [ctrl updateWithParams: params];
    return ctrl;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
